package cn.dakaqi.apps.group.admin.controller;

import cn.dakaqi.apps.group.admin.response.VolunteerVO;
import cn.dakaqi.apps.group.admin.shiro.ShiroDbRealm;
import cn.dakaqi.entities.Group;
import cn.dakaqi.entities.GroupVolunteer;
import cn.dakaqi.entities.Platform;
import cn.dakaqi.entities.PlatformGroup;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.services.GroupService;
import cn.dakaqi.services.GroupVolunteerService;
import cn.dakaqi.services.PlatformGroup2Service;
import cn.dakaqi.services.PlatformService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import com.mangofactory.swagger.annotations.ApiIgnore;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import org.springside.modules.web.MediaTypes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/5/12.
 */
@RestController
@RequestMapping(value = "/group")
@ApiIgnore
public class GroupController extends BaseController
{
    private static Logger logger = LoggerFactory.getLogger(GroupController.class);
    @Autowired
    GroupService groupService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    PlatformService platformService;
    @Autowired
    PlatformGroup2Service platformGroup2Service;

    @Override
    protected ModelAndView initModelAndView(String groupCode, String view,HttpServletRequest request)
    {
        ModelMap modelMap = super.initData(groupCode,request);
        return new ModelAndView(view, modelMap);
    }
    @Override
    protected void clearModelAndView(String groupCode,HttpServletRequest request)
    {
        redisClientTemplate.del(groupCode);
    }
    private Group getCurGroup(HttpServletRequest request)
    {
        return ((Group)request.getSession().getAttribute("curGroup"));
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView createForm(HttpServletRequest request)
    {

        Volunteer volunteer = this.volunteerService.findByUserId(getCurrentUserId());
        if(StringUtils.isBlank(volunteer.getCardNO()) || volunteer.getCardNO().toLowerCase().equals("null"))
        {
            ModelMap modelMap = super.initData("",request);
            String view = "settings/certification";
            ModelAndView modelAndView = new ModelAndView(view, modelMap);
            modelAndView.addObject("volunteer", volunteer);
            modelAndView.addObject("message", "请完善个人信息");
            return modelAndView;
        }


        String view = "group/groupForm",groupCode = "";
        Group curGroup = getCurGroup(request);
        if(null != curGroup)
            groupCode = curGroup.getGroupCode();

        ModelAndView modelAndView = initModelAndView(groupCode, view,request);
        Group newGroup = new Group();
        newGroup.setProvince("上海市");
        newGroup.setCity("上海市");
        newGroup.setDistrict("长宁区");
        modelAndView.addObject("newGroup", newGroup);
        modelAndView.addObject("action", "/create");
        return modelAndView;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RedirectView create(@Valid Group newGroup,HttpServletRequest request,RedirectAttributes redirectAttributes)
    {
//        Volunteer createUser = this.volunteerService.findByUserId(getCurrentUserId());
//        newGroup.setCreateUser(createUser);
//        newGroup.setServiceField(newGroup.getServiceField().replace(",",";"));
//        this.groupService.save(newGroup);
//        String url = request.getContextPath()+"/group/update?groupCode=" + newGroup.getGroupCode();
//        logger.info(url);
//        redirectAttributes.addFlashAttribute("message", "社团创建成功");
//        return new RedirectView(url);

        Volunteer createUser = this.volunteerService.findByUserId(getCurrentUserId());
        newGroup.setCreateUser(createUser);
        newGroup.setServiceField(newGroup.getServiceField().replace(",", ";"));
        newGroup.setClient(ConfigUtil.getClientId());
        this.groupService.save(newGroup);
        String url = request.getContextPath()+"/dashboard";
        redirectAttributes.addFlashAttribute("message", "社团创建成功");
        return new RedirectView(url);

    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public ModelAndView updateForm(@RequestParam("groupCode") String groupCode,HttpServletRequest request)
    {
        String view = "group/groupForm";
        if(StringUtils.isBlank(groupCode))
        {
            Group curGroup = getCurGroup(request);
            if (null != curGroup)
                groupCode = curGroup.getGroupCode();
        }
        ModelAndView modelAndView = initModelAndView(groupCode, view,request);
        modelAndView.addObject("newGroup", groupService.findByGroupCode(groupCode));
        modelAndView.addObject("action", "/update");
        return modelAndView;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public RedirectView update(@Valid @ModelAttribute("newGroup") Group newGroup,HttpServletRequest request,RedirectAttributes redirectAttributes)
    {
        if(StringUtils.isNotBlank(newGroup.getServiceField()))
            newGroup.setServiceField(newGroup.getServiceField().replace(",",";"));
        groupService.update(newGroup);
        String url = request.getContextPath()+"/group/update?groupCode=" + newGroup.getGroupCode();
        logger.info(url);
        redirectAttributes.addFlashAttribute("message", "社团修改成功");
        return new RedirectView(url);
    }

    @RequestMapping(value = "/setAdminPage", method = RequestMethod.GET)
    public ModelAndView setVolunteerPower(@RequestParam("groupCode") String groupCode,HttpServletRequest request)
    {
        String view = "group/setVolunteerPower";
        Group curGroup = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view,request);
        //查询当前社团的所有管理员
        List<GroupVolunteer> list = this.groupVolunteerService.findAdminByGroup(curGroup.getGroupCode());
        modelAndView.addObject("list",list);
        return modelAndView;
    }
    @RequestMapping(value = "/volunteers", method = RequestMethod.GET)
    public ModelAndView volunteers(@RequestParam("groupCode") String groupCode,@RequestParam("pageNumber") int pageNumber,HttpServletRequest request)
    {
        String view = "group/volunteers";
        Group curGroup = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view,request);
        //查询当前社团的所有管理员
        Page<GroupVolunteer> data = this.groupVolunteerService.queryGroupCode(curGroup.getGroupCode(), DKQConstant.APPLY_STATUS_OK,pageNumber);
        modelAndView.addObject("data",data);
        return modelAndView;
    }
    @RequestMapping(value = "/searchVolunteer", method = RequestMethod.GET)
    public ModelAndView searchVolunteer(@RequestParam("name") String name,HttpServletRequest request)
    {
        String view = "group/volunteers";
        Group curGroup = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view,request);
        //查询当前社团的所有管理员
        Page<GroupVolunteer> data = this.groupVolunteerService.findByVolunteerName(curGroup.getGroupCode(), name, 1);
        modelAndView.addObject("data",data);
        return modelAndView;
    }
    @RequestMapping(value = "/searchMonitor", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> searchMonitor(@RequestParam("realName") String realName,HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        String message = "设置成功";
        try
        {
            Group curGroup = getCurGroup(request);
            GroupVolunteer groupVolunteer = this.groupVolunteerService.searchMonitor(curGroup.getGroupCode(),realName);
            if(null != groupVolunteer)
            {
                Map<String,Object> resultMap = new HashMap<String, Object>();
                resultMap.put("volunteer", VolunteerVO.buildVO(groupVolunteer.getVolunteer()));
                jsonResult.setData(resultMap);
                jsonResult.setCode(JsonResult.CODE_SUCCESS);
                jsonResult.setMessage(message);
            }
            else
            {
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage("查无此人");
            }

        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            message = e.getMessage();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            message = "查无此人";
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }

        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }

    @RequestMapping(value = "/setAdmin", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> setAdmin(@RequestParam("id") long id,@RequestParam("role") int role,HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        String message = "设置成功";
        try
        {
            Volunteer volunteer = (Volunteer)request.getSession().getAttribute("volunteer");
            this.groupVolunteerService.setAdmin(id,role,volunteer.getMemberCode());
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage(message);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            message = e.getMessage();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            message = "设置失败";
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }

        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }

    @ModelAttribute
    public void getGroup(@RequestParam(value = "id", required = false) Long id, Map<String, Object> map)
    {
        if (id != null)
        {
            Group newGroup = this.groupService.findOne(id);
            map.put("newGroup", newGroup);
        }
    }


    @RequestMapping(value = "/joinOrg", method = RequestMethod.GET)
    public ModelAndView joinOrgPage(HttpServletRequest request)
    {
        String view = "group/joinOrgPage";
        Group curGroup = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view,request);
        //查询所有平台
        Page<Platform> data = platformService.findAll(1, DKQConstant.DEL_NO);
        //查询当前社团已挂了哪些平台
        List<PlatformGroup> platformGroups = platformGroup2Service.findByGroup(curGroup.getId());

        modelAndView.addObject("platforms",data.getContent());
        modelAndView.addObject("platformGroups",platformGroups);
        return modelAndView;
    }

    @RequestMapping(value = "/joinOrg", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> joinOrg(@RequestParam("platform") long platform,@RequestParam("parentCode") String  parentCode,HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        String message = "挂靠成功";
        try
        {
            Group group = getCurGroup(request);
            Volunteer volunteer = (Volunteer)request.getSession().getAttribute("volunteer");
            this.groupService.joinOrg(group.getGroupCode(), platform, parentCode, volunteer.getMemberCode(),0);
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage(message);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            message = e.getMessage();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            message = "挂靠失败";
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }

        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }
    @RequestMapping(value = "/cancelJoinOrg", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> cancelJoinOrg(@RequestParam("id") long id,HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        String message = "取消成功";
        try
        {
            this.platformGroup2Service.delById(id);
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage(message);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            message = e.getMessage();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            message = "取消失败";
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }

        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }

    private Long getCurrentUserId()
    {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }
    private void clearRedisCache(String key)
    {
        redisClientTemplate.del("");
    }

}
